export default function applayMiddleware(...wares: any[]) {
  return (createStore: Function) => (reducer:Function) => {
      const store = createStore(reducer)
      let { dispatch } = store

      const midApi = {
        getState: store.getState,
        dispatch: (action: IAction) => dispatch(action)
      }

      const chain = wares.map(w => w(midApi))

      dispatch = compose(...chain)(store.dispatch)

      return {
        ...store,
        dispatch
      }
  }
}

function compose(...funs: any[]) {
  if (funs.length === 0) {
    return (x: any) => x;
  }
  if (funs.length === 1) {
    return funs[0];
  }
  return funs.reduce((a, b) => (...args:any) => a(b(...args)))
}
